package com.zhupf.binarySearch;

/**
 * @author zhupf
 * @date 2024年01月17日 11:05
 * @Description
 *
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 */
public class SearchRange {

    public static void main(String[] args) {
        int[] nums = {1};
        searchRange(nums,1);
    }

    public static int[] searchRange(int[] nums, int target) {
        int[] res = new int[2];
        res[0] = -1;
        res[1] = -1;
        int left = 0;
        int right = nums.length -1;
        while (left <= right){
            int mid = left + (right - left)/2;
            if(nums[mid] == target){
                int res0  = mid;
                int res1  = mid;
                while (res0>= left && nums[res0] == target){
                    res0--;
                }
                res[0] = res0+1;
                while (res1 <= right && nums[res1] == target ){
                    res1++;
                }
                res[1] = res1 -1;
                break;
            }else if(target < nums[mid]){
                right = mid -1;
            }else {
                left = mid +1;
            }
        }
        return res;
    }

}
